package com.example.locations;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private static Context context;
    private int counts = 0;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = getApplicationContext();
        //requirePermission();
        TextView mFileContentView = (TextView) findViewById(R.id.TextView0);
        mFileContentView.setMovementMethod(ScrollingMovementMethod.getInstance());
        Button start = findViewById(R.id.start);
        Button stop = findViewById(R.id.stop);
        Button clean = findViewById(R.id.clean);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTime();
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
            }
        });
        clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView textView = findViewById(R.id.TextView0);
                textView.setText("");
                counts = 0;
            }
        });


    }

    public void startTime(){
        Toast.makeText(getApplicationContext(),"开始执行定时任务",Toast.LENGTH_LONG).show();
        timer = new Timer();
        Handler handler = new Handler() {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                Location location = (Location) msg.obj;
                TextView textView = findViewById(R.id.TextView0);
                textView.append(location.getLatitude()+";"+location.getLongitude()+"\n");
                counts++;
                if (counts>=50){
                    textView.setText("");
                    counts = 0;
                }
                //System.out.println(location.getLatitude()+";"+location.getLongitude()+"\n");
            }
        };
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                MyLocation.LocationResult locationResult = new MyLocation.LocationResult(){
                    @Override
                    public void gotLocation(Location location){
                        Message message = new Message();
                        message.what = 1;
                        message.obj = location;
                        handler.sendMessage(message);
                    }
                };
                MyLocation myLocation = new MyLocation();
                myLocation.getLocation(MainActivity.this, locationResult);

            }
        };
        timer.schedule(task,1000,1000);
    }


    public static Context getContext(){
        return context;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1){
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        TextView textView = findViewById(R.id.TextView0);
                        //MyToast.showToast("权限未申请");
                        textView.setText("权限未申请");
                    }
                }else {
                    MyLocation.LocationResult locationResult = new MyLocation.LocationResult(){
                        @Override
                        public void gotLocation(Location location){
                            setLocation(location);
                        }
                    };
                    MyLocation myLocation = new MyLocation();
                    myLocation.getLocation(MainActivity.this, locationResult);
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private void requirePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(MainActivity.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},
                        1);
            }else{
                MyLocation.LocationResult locationResult = new MyLocation.LocationResult(){
                    @Override
                    public void gotLocation(Location location){
                        setLocation(location);
                    }
                };
                MyLocation myLocation = new MyLocation();
                myLocation.getLocation(MainActivity.this, locationResult);
            }
        }
    }

    private void setLocation(Location location) {
        if (location!=null) {
            String mfeatureName = null;
            Geocoder geocoder = new Geocoder(MainActivity.this);
            List<Address> addList = null;// 解析经纬度
            try {
                TextView textView = findViewById(R.id.TextView0);
                textView.setText("");
                textView.append(location.getLatitude()+";"+location.getLongitude()+"\n");
                addList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}